const tool = {
    //验证必填项
    async genTreeList(list, parent_id) {
        let retList = [];
        for (var i = 0; i < list.length; i++) {
            let treeItem = list[i];
            treeItem.title = treeItem.menu_name;
            treeItem.value = treeItem.menu_id;
            treeItem.key = treeItem.menu_id;
            console.log(`${parent_id} == ${treeItem.menu_id}`, parent_id == treeItem.menu_id);
            if (parent_id == treeItem.parent_id) {
                let childList = await tool.genTreeList(list, treeItem.menu_id);
                if (childList.length > 0) {
                    treeItem.children = childList;
                }
                retList.push(treeItem);
            }
        }
        return retList;
    },
    toTreeList(data, primary_key, parent_key, mapkey) {
        let result = [];

        //检验数据是否符合规范
        if (!Array.isArray(data) || (!primary_key) || (!parent_key)) {
            return result
        }
        //键值映射关系
        if (!Array.isArray(mapkey)) {
            mapkey = [];
        }

        data.forEach(item => {
            delete item.children;
        });
        let map = {};
        data.forEach(item => {
            map[item[primary_key]] = item;
        });
        data.forEach(item => {
            let parent = map[item[parent_key]];
            //关系映射
            for (var i = 0; i < mapkey.length; i++) {
                let mapItem = mapkey[i];
                //锁定映射关系是否合法
                if (Array.isArray(mapItem)) {
                    if (mapItem.length == 2) {
                        item[mapItem[0]] = item[mapItem[1]];
                    }
                }
            }
            if (parent) {
                (parent.children || (parent.children = [])).push(item);
            } else {
                result.push(item);
            }
        });
        return result;
    }
}

module.exports = tool;